<template>
	<el-col :span="24" id="content2_container">
		<!-- <el-col :span="20" :offset="2" id="transaction_tend"> -->

			<el-col :span="24" id="txtend">
				<span id="txicon"></span>
				<span id="txtendtitle">交易趋势</span>
				<el-button type="text" class="diagrambtn" v-bind:class="btnObject3()" v-on:click="diagramchange($event)">24小时</el-button>
				<el-button type="text" class="diagrambtn" v-bind:class="btnObject2()" v-on:click="diagramchange($event)">1周</el-button>
				<el-button type="text" class="diagrambtn" v-bind:class="btnObject1()" v-on:click="diagramchange($event)">1月</el-button>
			</el-col>

			<el-col :span="20" class="charts bgc" >
				<div id="myChart"></div>
				<!-- <div class="loading" v-if="loading">
					<i class="el-icon-loading"/>
					<span>加载中</span>
				</div> -->
				
			</el-col>

			<el-col :span="4" id="transaction_num" class="bgc">

				<div id="past_transaction_container">
					<div id="past_transaction_value" class="ntitle">{{past30_tr}}</div>
					<div id="past_transaction" class="ctitle">近30日交易数</div>
				</div>

				<div class="today_transaction_container">
					<div class="ntitle">{{today_tr}}</div>
					<div class="today_transaction ctitle">今日新增交易数</div>
				</div>

				<div class="today_transaction_container">
					<div class="xtitle">{{(today_trprice / 10000).toFixed(2)}}万元</div>
					<div class="today_transaction ctitle">今日总交易额</div>
				</div>

			</el-col>

		<!-- </el-col> -->
	</el-col>
</template>

<script>

	import herderjs from "../utils/header.js"

	export default {

		data() {
	        return {
	        	list: "",
		        past30_tr: 0,
		        today_tr: 0,
		        today_trprice: 0,
		        isActive1: false,
		        isActive2: false,
		        isActive3: true,
		        mainChart: "",
		        loading: true,
		        refresh_flag: true
	        }
	    },

	    methods:{  
	    	setData: function() {
				let param = {period:30}
				this.$api.post('blockchain/txsAndAmount', param, r => {
					this.past30_tr = r.data.pastTxs
					this.today_tr = r.data.txs
					this.today_trprice = r.data.price
				})
	    	},

	    	startValueIndex (type,arrayl) {
		    	switch (type) {
		    		case "day":
		    			return arrayl - 20
		    		case "week":
		    			return arrayl - 30
		    		case "month":
		    			return arrayl - 31
		    	}
		    },

	    	diagram: function (period) {
	    		//获取过去30天的交易记录,设定请求接口参数
		    	let param = {period:period}
		    	var myChart=document.getElementById('myChart')
		    	// myChart.document.getElementById('myChart');
		    	let echarts = require('echarts/lib/echarts')
		    	// 基于准备好的dom，初始化echarts实例
				if (this.mainChart != "") {
					// console.log(this.mainChart === "")
					this.mainChart.clear()
				}
				this.mainChart = echarts.init(myChart)	
				this.mainChart.showLoading();
		    	this.$api.post('blockchain/visualization', param, r => {
		    		this.loading = false
		    		//从后端获取数据后回调
					this.list = r
					
				    let chartBox=document.getElementsByClassName('charts')[0]
				    

				    var stock = []
				    var sell = []
				    var trade = []
				    var datearrayf = []

				    let inc
					switch (param.period) {
						case "day":
							inc = 10
							break;
						case "week":
							inc = 60
							break;
						case "month":
							inc = 1
							break;
					}
					// for (var i=0;i<r.data.length;i+=inc) {
					// 	stock.push(Math.round(r.data[i].buyValue))
					// 	sell.push(Math.round(r.data[i].sellValue))
					// 	trade.push(r.data[i].txs)
					// 	datearrayf.push(r.data[i].time)
					// }

					let ss = 0
					let sv = 0
					let stx = 0
					for (var i=0;i<r.data.length;i+=inc) {
						ss = 0
						sv = 0
						stx = 0
						for (let q = i; q < i + inc; q+=1) {
							if (q < r.data.length) {
								ss += r.data[q].buyValue
								sv += r.data[q].sellValue
								stx += r.data[i].txs
							}
						}
						stock.push( (ss / 10000).toFixed(3) )
						sell.push( (sv / 10000).toFixed(3) )
						trade.push(stx)
						datearrayf.push(r.data[i].time)
					}
					
					
				    this.mainChart.setOption({
				        tooltip : {
				            trigger: 'axis',
				            axisPointer: {
				                type: 'shadow',
				                label: {
				                    show: true
				                }
				            },
			   				formatter: function (params, ticket, callback) {
				            	var res = ""
							    for(let i = 0;i < params.length;i++) {
							    	if (i === 0) {
							    		if (params[i].seriesName === '进货金额') {
							    			res += params[i].name + '<br/>' + params[i].marker + "进货金额：" + params[i].value + "万元"
							    		} else if (params[i].seriesName === '销售金额') {
							    			res += params[i].name + '<br/>' + params[i].marker + "销售金额：" + params[i].value + "万元"
							    		} else {
							    			res += params[i].name + '<br/>' + params[i].marker + "交易量：" + params[i].value
							    		}
							    	} else {
							    		if (params[i].seriesName === '进货金额') {
							    			res += '<br/>' + params[i].marker + "进货金额：" + params[i].value + "万元"
							    		} else if (params[i].seriesName === '销售金额') {
							    			res += '<br/>' + params[i].marker + "销售金额：" + params[i].value + "万元"
							    		} else {
							    			res += '<br/>' + params[i].marker + "交易量：" + params[i].value
							    		}
							    	}
							    	
							    }
							    return res;
							}
				        },
				        calculable : true,
				        legend: {
				            data:['交易量', '进货金额', '销售金额'],
				            itemGap: 5
				        },
				        grid: {
				            left: '2%',
				            right: '0',
				            bottom: '10%',
				            top: '15%',
				            containLabel: true
				        },
				        xAxis: [{
				            type: 'category',
				            data: datearrayf,
				            axisLabel: {
				                formatter: function (value) {
				                    let s = value
				                    switch (param.period) {
										case "day":
											s = s.substring(value.length-5);
											break;
										case "week":
											s = s.substring(value.length-5);
											break;
										case "month":
											// s = s.substring(value.length-8);
											s = s.substring(value.length-5)
											break;
										default: break;
									}
									return s
				                }
				            },
				            // splitLine: {
				            //     show: false
				            // },
				            // boundaryGap: false
				        }],
				        yAxis: [
				            {
				            	name: '金额（万元）',
				            	nameGap: 10,
				            	// nameTextStyle: {
				            	// 	align: "left"
				            	// },
				            	splitNumber: 5,
					            splitLine: {
					                show: true
					            },
					            scale: true
					        },
					        {
					        	name: '交易量',
					        	nameGap: 10,
					        	show: true,
					        	splitNumber: 5,
					        	splitLine: {
					                show: false
					            },
					            // scale: true
					        }
				        ],

				        dataZoom: [
				            {
				                show: true,
				                type: 'slider',
				                height: '8%',
				                bottom: '1%',
				                width: '76%',
				                // left: '9%',
				                right: '12%',
				                startValue: this.startValueIndex(param.period,datearrayf.length),
				                endValue: datearrayf.length - 1,
				                // start: 97,
				                // end: 100
				            },
				            {
				                type: 'inside',
				                startValue: this.startValueIndex(param.period,datearrayf.length),
				                endValue: datearrayf.length - 1
				            },
				            // {
				            //     show: true,
				            //     yAxisIndex: 0,
				            //     filterMode: 'empty',
				            //     width: '10%',
				            //     height: '80%',
				            //     showDataShadow: false,
				            //     left: '97%'
				            // }
				        ],
				        
				        series: [
					        {
				                name: '进货金额',
				                type: 'bar',
				                // animation: false,
				                data: stock
				            },
				            {
				                name: '销售金额',
				                type: 'bar',
				                // animation: false,
				                data: sell
				            },
				            {
				            	name: '交易量',
				            	type: 'line',
				            	yAxisIndex: 1,
				            	// animation:false,
				            	data: trade
				            }

				        ]
				    },true);
				    //生成表格后隐藏loading动画
					this.mainChart.hideLoading()
					//重新调整表格尺寸
					window.onresize = this.mainChart.resize;
					
				})
	    	},

	    	btnObject1 () {
	    		return {
	    			active: this.isActive1,
	    		}
	    	},	

	    	btnObject2 () {
	    		return {
	    			active: this.isActive2,
	    		}
	    	},	

	    	btnObject3 () {
	    		return {
	    			active: this.isActive3
	    		}
	    	},	

	    	diagramchange: function (event) {
	    		var e = event.target.innerText
	    		var p = ""
	    		if (e === "1月") {
	    			this.isActive1 = true
	    			this.isActive2 = false
	    			this.isActive3 = false
	    			p = "month"
	    		} else if (e === "1周") {
	    			this.isActive1 = false
	    			this.isActive2 = true
	    			this.isActive3 = false
	    			p = "week"
	    		} else if (e === "24小时") {
	    			this.isActive1 = false
	    			this.isActive2 = false
	    			this.isActive3 = true
	    			p = "day"
	    		}
	    		this.diagram(p)
	    	}
	    },

	    mounted(options){
	    	this.diagram("day")
	    	this.setData()
	    	herderjs.$on('refresh_flag', (data) => { 
				this.refresh_flag = data
			})
	    	//监听herderjs中的数据，实时接收herder.vue中传过来的值
	    	herderjs.$on('val', (data) => {
	    		if (data===1 && this.refresh_flag) {
	    			// console.log("22222222")
	    			let _this = this
					setTimeout(function () {
						// console.log("2222222")
		    			let param = {period:30}
						_this.$api.post('blockchain/txsAndAmount', param, r => {
							_this.past30_tr = r.data.pastTxs
							_this.today_tr = r.data.txs
							_this.today_trprice = r.data.price
							herderjs.$emit('val', data + 1)
						})
					}, 10000)
	    		}
	    		
			})
		}
		
	}
</script>


<style scoped>

	#content2_container {
		margin-top: 0.3%;
		height: 33%;
		width: 99.3%;
		margin-left: 0.3%;
		box-shadow: 0 2px 4px 0 rgba(179,179,179,0.50);
	}

	#txtend {
		/*height: 100%;*/
		height: 14%;
		background-color: rgb(255,255,255);
		box-shadow: 0 1px 2px 0 rgba(179,179,179,0.50);
		/*font-size: 1vw;*/
		margin-bottom: 0.3%;
		border-radius:2px;
	}

	#txicon {
		position: relative;
		float: left;
		width: 2.9%;
		height: 74%;
		margin-top: 0.5%;
		margin-left: 0.7%;
		background-image:url('../assets/icon_trend.png');
		background-size:100% 100%;
		background-repeat:no-repeat;
	}

	#txtendtitle {
		font-size: 0.9vw;
		color: #333333;
		float: left;
		position: relative;
		margin-top: 0.82%;
		margin-left: 0.1%;
	}

	.diagrambtn {
		float: left;
		position: relative;
		top: 50%;
		margin-top: -20px;
		margin-left: 1.5%;
		color: #333333;
	}

	.diagrambtn:hover {
		color: #1DB2BF;
	}

	.active {
		color: #1DB2BF;
	}

	.bgc {
		background-color: rgb(255,255,255);
		/*margin-bottom: 40px;*/
		height: 85.5%;
	}

	.charts {
		/*height: 87%;*/

	}

	.ctitle {
		font-size: 0.8vw;
		font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
		color: rgb(255,255,255);
		margin-top: 3%;
		margin-bottom: 7%;
	}

	.ntitle {
		font-size: 1.2vw;
		font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
		color: rgb(255,255,255);
		margin-top: 1%;
	}

	.xtitle {
		font-size: 0.95vw;
		font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
		color: rgb(255,255,255);
		margin-top: 1%;
	}

	#myChart {
		width: 100%;
		height: 100%;
	}


	#transaction_num {
		/*height: 100%;*/
		text-align: center;
	}

	#past_transaction_container {
		margin-top: 4%;
		padding: 5%;
		background-color: #4D4D4D;
		margin-left: 7%;
		height: 20%;
		width: 70%;
		border-radius:2px;
	}

	.today_transaction_container {
		margin-top: 7%;
		padding: 5%;
		background-color: #4D4D4D;
		margin-left: 7%;
		height: 20%;
		width: 70%;
		border-radius:2px;
	}
	
</style>